package com.flowable.service.impl;

import com.flowable.service.LeaveService;
import org.flowable.engine.RepositoryService;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.TaskService;
import org.flowable.engine.repository.ProcessDefinition;
import org.flowable.task.api.Task;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 长沙先飞信息科技有限公司<br>
 * Created with IntelliJ IDEA.<br>
 * Date:2024/7/8<br>
 * Time:13:02<br>
 * 功能描述：<br>
 *
 * @author huang hou chun
 * @since JDK 1.8 <br>
 * Copyright (c) 2023 www.csxfrj.com System Incorporated All Rights Reserved.
 */
@Service
public class LeaveServiceImpl implements LeaveService {

    @Resource
    private RuntimeService runtimeService;
    @Resource
    private TaskService taskService;
    @Resource
    private RepositoryService repositoryService;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void startProcess() {
        List<ProcessDefinition> processDefinitionList = repositoryService.createProcessDefinitionQuery()
                .processDefinitionKey("leave")
                .orderByProcessDefinitionId()
                .desc().list();
        String proDefId = processDefinitionList.get(0).getId();

        final Map<String, Object> formProps = new HashMap<>();
        formProps.put("reason", "家里有事");
        formProps.put("startTime", LocalDate.now());
        formProps.put("endTime", LocalDate.now());
        String outcome = "outStr";
        runtimeService.startProcessInstanceWithForm(proDefId, outcome, formProps, "表单任务");
    }

    @Override
    public void complete(String groupName) {
        List<Task> taskList = taskService.createTaskQuery()
                .processDefinitionKey("leave")
                .taskCandidateGroup(groupName)
                .orderByTaskCreateTime()
                .desc()
                .list();
        String taskId = taskList.get(0).getId();
        Map<String, Object> param = new HashMap<>();
        param.put("leaderApproved", true);

        taskService.complete(taskId, param);
    }
}
